package com.compass.doctor.ui.setting

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityReportBinding
import com.compass.doctor.preview.PreviewPicActivity
import com.compass.doctor.ui.home.adapter.GridImageAdapter
import com.compass.doctor.ui.home.viewmodel.MedicalCareViewModel
import com.compass.doctor.ui.patient.viewmodel.PatientViewModel
import com.compass.doctor.utils.SelectPicturesUtil
import com.compass.framework.R
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toJson
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.FullyGridLayoutManager
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.getStringFromResource
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import java.io.File
import java.lang.ref.WeakReference

/**
 * Description： 举报界面
 * Date:2024/2/18 15:27
 */
class ReportActivity : BaseVBActivity<ActivityReportBinding>() {


    companion object {
        fun start(context: Context) {
            val intent = Intent(context, ReportActivity::class.java)
            context.startActivity(intent)
        }
    }


    private val patientViewModel: PatientViewModel by viewModels()
    private val medicalCareViewModel: MedicalCareViewModel by viewModels()
    private var success: ArrayList<String> = ArrayList()//上传成功的集合
    private var fails: ArrayList<String> = ArrayList()//上传失败的集合

    private val maxSelectNum = 9
    private var mPic: List<LocalMedia> = ArrayList()
    private lateinit var mAdapter: GridImageAdapter
    private var index: Int = 0//记录下标（从第一张开始）
    private val weakHandler by lazy { WeakReferenceHandler(this) }

    private lateinit var content: String

    class WeakReferenceHandler(obj: ReportActivity) :
        Handler(Looper.getMainLooper()) {

        private val mRef: WeakReference<ReportActivity> = WeakReference(obj)
        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                when (msg.what) {
                    1 -> {
                        //上传操作
                        medicalCareViewModel.upload(File(mPic[index].compressPath))
                    }

                    2 -> {
                        //完成操作
                        dismissLoading()
                        setData()
                        LogUtil.e("http_data====${success.toJson()}")

                    }

                    3 -> {
                        //失败
                        dismissLoading()
                        showToast("图片上传失败")
                    }
                }
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {

        mAdapter = GridImageAdapter(this, mPic)
        mAdapter.selectMax = maxSelectNum
        mBinding.recycler.apply {
            val manager = FullyGridLayoutManager(
                this@ReportActivity,
                4, GridLayoutManager.VERTICAL, false
            )
            layoutManager = manager
            itemAnimator?.let {
                (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            }
            adapter = mAdapter
        }


    }

    override fun intListener() {

        mAdapter.setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
            override fun openPicture() {
                isReadWriteGranted()
            }

            override fun onItemClick(v: View?, position: Int) {
                PreviewPicActivity.start(
                    this@ReportActivity,
                    position,
                    mAdapter.data
                )
            }
        })

        mBinding.tvSubmit.onClick {

            content = mBinding.edtDiseaseDescription.text.toString().trim()
            if (content.isEmpty()) {
                showToast("请输入举报内容")
                return@onClick
            }

            if (mPic.isNotEmpty()) {
                showLoading("正在上传图片...")
                weakHandler.sendEmptyMessage(1)
            } else {
                showToast("图片不能为空")
            }

        }
    }

    override fun initData() {
        medicalCareViewModel.updateLiveData.observe(this) {
            index++
            it?.let {
                success.add(it)
                if (index < mPic.size) {
                    //继续上传
                    weakHandler.sendEmptyMessage(1)
                } else {
                    //结束上传
                    weakHandler.sendEmptyMessage(2)
                }
            } ?: kotlin.run {
                //失败
                weakHandler.sendEmptyMessage(3)
                fails.add(mPic[index].compressPath)//后续优化失败续传
            }
        }

        patientViewModel.createSuccessLiveData.observe(this) {
            it?.let {
                showToast("举报成功，请耐心等待")
                finish()
            }
        }
    }


    private fun setData() {
        patientViewModel.createReporting(content, success)
    }

    /**
     * 判断是否有读写拍照等权限
     */
    private fun isReadWriteGranted() {
        //判断是否有权限
//        if (XXPermissions.isGranted(this, Permission.MANAGE_EXTERNAL_STORAGE, Permission.CAMERA)) {
        if (XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE, Permission.CAMERA)) {
            choosePic()
        } else {
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(com.compass.doctor.R.string.permission_explain))
                .setMessage(getStringFromResource(com.compass.doctor.R.string.image_permission_logs))
                .setConfirm(getStringFromResource(R.string.default_confirm))
                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    requestPermissions()
                    it?.dismiss()
                }.create().show()
        }
    }


    /**
     * 请求权限
     */
    private fun requestPermissions() {
        XXPermissions.with(this)
//            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(Permission.CAMERA)
            .unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        TipsToast.showTips("获取部分权限成功，但部分权限未正常授予")
                        return
                    }
                    choosePic()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {

                        TipsToast.showTips("被永久拒绝授权，请手动授予相关权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(
                            this@ReportActivity,
                            permissions
                        )
                    } else {
                        TipsToast.showTips(com.compass.doctor.R.string.default_agree_permission)
                    }
                }
            })
    }

    /**
     * 选择图片
     */
    private fun choosePic() {
        SelectPicturesUtil.selectPicturesMultiple(
            this@ReportActivity, mAdapter.data,
            callbackListener = object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia?>) {
                    val isMaxSize = result.size == mAdapter.selectMax
                    val oldSize: Int = mAdapter.data.size
                    mAdapter.notifyItemRangeRemoved(
                        0,
                        if (isMaxSize) oldSize + 1 else oldSize
                    )
                    mAdapter.data.clear()
                    mAdapter.data.addAll(result)
                    mPic = mAdapter.data
                    mAdapter.notifyItemRangeInserted(0, result.size)
                }

                override fun onCancel() {

                }
            })
    }
}